#include "UIForm.h"

namespace FinalRendering
{
	namespace Editor
	{
		using namespace GxWinGUI;
		using namespace GxRendering::UI;

		UIForm::UIForm()
		{
			Global::Init();
			BeginGLDrawing();
			ui = new GxRendering::UI::UIEntry(GetClientWidth(), GetClientHeight());
			Global::MakeCurrent(ui.operator ->());
			
			//tmrUI.Interval = 50;
			//tmrUI.OnTick.Bind(this, &UIForm::tmrUI_Tick);

			OnShow.Bind(this, &UIForm::form_internal_Show);
			OnClose.Bind(this, &UIForm::form_internal_Close);

		}

		UIForm::~UIForm()
		{
			BeginGLDrawing();
			ui = 0;
		}

		bool UIForm::ProcessMessage(GxWinGUI::WinMessage msg)
		{
			auto ctx = wglGetCurrentContext();
			auto dc = wglGetCurrentDC();
			bool rs = GLForm::ProcessMessage(msg);
			if (ui)
			{
				
				BeginGLDrawing();
				Global::MakeCurrent(ui.operator ->());
				ui->HandleSystemMessage(msg.hWnd, msg.message, msg.wParam, msg.lParam);
			}

			
			Refresh();
			wglMakeCurrent(dc, ctx);
			return rs;
		}

		void UIForm::Refresh()
		{
			if (ui && GetVisible())
			{
				Global::MakeCurrent(ui.operator ->());
				glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
				ui->DrawUI();
				SwapBuffers(hDC);
			}
		}

		void UIForm::form_internal_Show(Object * sender, GxWinGUI::EventArgs e)
		{
			tmrUI.StartTimer();
		}

		void UIForm::form_internal_Close(Object * sender, GxWinGUI::WindowCloseEventArgs & e)
		{
			tmrUI.StopTimer();
		}

		void UIForm::tmrUI_Tick(Object * sender, GxWinGUI::EventArgs e)
		{
		/*	if (ui && GetVisible())
			{
				
				BeginGLDrawing();
				Global::MakeCurrent(ui.operator ->());
				glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
				ui->DrawUI();
				EndGLDrawing();
			}*/
		}
	}
}